//
//  ActivityVC.m
//  NewNest
//
//  Created by hesiyao on 16/1/19.
//  Copyright © 2016年 www.lanou3g.com蓝鸥科技. All rights reserved.
//

#import "ActivityVC.h"
#import <AFHTTPSessionManager.h>
#import <AFNetworking.h>
#import "ActivityCell.h"
#import "ActivityModal.h"
#import <UIImageView+WebCache.h>
#import "AvtivityDetailPageVC.h"
#import <MJRefresh.h>
@interface ActivityVC () <UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, retain) UITableView *tableview;
@property (nonatomic, retain) NSMutableArray *dataArr;
@property (nonatomic, assign) NSInteger number;/**< 用来保存加载的动态值 */
@end

@implementation ActivityVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //navigation设置
    self.navigationItem.title = @"优选活动";
    
    //数据处理
    [self dataHandler];
    
    // 视图创建
    [self createSubviews];
    //隐藏导航栏
    [self hidden];
    
    //给加载时的动态值赋初值
    self.number = 2;
    //下拉刷新 上拉加载
    [self refresh];
}

/// 数据处理
- (void)dataHandler
{
    NSString *urlStr = @"http://ihome.cmfmobile.com:8080/sp/custom/getGoodActivity.do?pn=1";
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    [session GET:urlStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"活动解析成功");
        NSMutableArray *arr = responseObject;
        self.dataArr = [ActivityModal modelHanderWithArray:arr];
        [_tableview reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"活动解析失败");
    }];
    
    //下拉刷新结束
    [self.tableview.mj_header endRefreshing];
}

/// 视图创建
- (void)createSubviews
{
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    _tableview.delegate = self;
    _tableview.dataSource = self;
    [_tableview registerClass:[ActivityCell class] forCellReuseIdentifier:@"cell"];
    [self.view addSubview:_tableview];
    [_tableview release];
}

// 设置cell个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArr.count;
}

// 设置cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ActivityCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    if (_dataArr.count != 0) {
        ActivityModal *m = _dataArr[indexPath.row];
        cell.titleLabel.text = m.name;
        [cell.imgView sd_setImageWithURL:[NSURL URLWithString:m.logo]];
        cell.dateLabel.text = m.time;
        cell.addressLabel.text = m.areaDetail;
        return cell;
        
    }else{
        return cell;
    }
}

// 设置cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return self.view.frame.size.height / 6;
}

// 点击进去详情
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    AvtivityDetailPageVC *activityVC = [[AvtivityDetailPageVC alloc] init];
    ActivityModal *m = _dataArr[indexPath.row];
    activityVC.modal = m;
    [self.navigationController pushViewController:activityVC animated:YES];
}

- (void)hidden
{
    // 导航栏隐藏设置
    if ([self respondsToSelector:@selector(automaticallyAdjustsScrollViewInsets)]) {
        // 取消ScrollView的内容自动调整
        self.automaticallyAdjustsScrollViewInsets = NO;
        //tableView边界预留
        UIEdgeInsets insets = self.tableview.contentInset;
        // 让上边界的预留值和导航栏相等
        insets.top = self.navigationController.navigationBar.bounds.size.height;
        //把修改后的边界预留值赋给tableView
        self.tableview.contentInset = insets;
        // 滚动指标点到滚到视图的边缘的距离
        self.tableview.scrollIndicatorInsets = insets;
    }
}

// 导航栏滚动
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    if (velocity.y > 0) {
        self.navigationController.navigationBar.hidden = YES;
        self.tabBarController.tabBar.hidden = YES;
    }else{
        self.navigationController.navigationBar.hidden = NO;
        self.tabBarController.tabBar.hidden = NO;
    }
}

// 下拉刷新 上拉加载
- (void)refresh
{
    // 下拉加载
    self.tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(dataHandler)];
    [self.tableview.mj_header beginRefreshing];
    
    //上拉加载
    self.tableview.mj_footer = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    //判断数据不为空 请求新的数据
    //因为只能加载两次 所以要盘点一下要小于3
    if (_dataArr.count != 0 || self.number <= 3) {
        [self.tableview.mj_footer beginRefreshing];
    }
}

/// 上拉加载方法
- (void)loadNewData
{
    NSString *urlStr = [NSString stringWithFormat:@"http://ihome.cmfmobile.com:8080/sp/custom/getGoodActivity.do?pn=%ld", self.number];
    [[AFHTTPSessionManager manager] GET:urlStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"优选活动加载成功");
        //创建新数组保存新的数据
        NSArray *newDataArr = [NSArray array];
        newDataArr = [ActivityModal modelHanderWithArray:responseObject];
        //将新的数据加入数据数组里面
        for (NSInteger i = 0; i < newDataArr.count; i++) {
            if (i != 0) {
                [_dataArr addObject:newDataArr[i]];
            }
        }
        // 刷新tableView
        [self.tableview reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"优选活动加载失败");
    }];
    
    // 结束上拉加载
    [self.tableview.mj_footer endRefreshing];
    // 动态值加1
    self.number += 1;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
